from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate,login  # 自带 进行用户名密码验证 登录方法
from django.contrib.auth.backends import ModelBackend  # 替补
from django.db.models import Q # 或集
from django.views.generic.base import View  # 调用视图  基于类实现

from users.forms import LoginForm, RegisterForm
from users.models import UserProfile, EmailVerifyRecord

# 市面 各种登录方式
from util.email_send import send_cus_mail


class CustomerBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # 获取用户名  去验证密码
            # 逗号表交集  | 表或
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

# 基于方式实现  FBV
# def user_login(request):
#     if request.method == 'POST':
#         username = request.POST.get('username')
#         password = request.POST.get('password')
#         # 自定义的  密码为密文  所以不能直接做比对
#         # user = UserProfile.objects.get(username=username)
#         # if user.password == password:
#         #     print('12233')
#         # else:
#         #     print('2222')
#
#         # Django 自带
#         # 1. 验证    只是单纯的用户名密码验证，还没进行登录操作
#         user = authenticate(username=username,password=password)
#         # 如果用户存在
#         if user:
#             # 2.  进行登录操作
#             login(request,user)
#             return HttpResponse('hello django')
#         else:
#             return render(request,'users/login.html',{})
#     elif request.method =='GET':
#         return render(request,'users/login.html',{})


# 基于类实现登录 CBF
class LoginView(View):
    def get(self,request):
        return render(request,'users/login.html',{})
    def post(self,request):
        login_form = LoginForm(request.POST)
        if  login_form.is_valid():
            # username = request.POST.get('username','')
            # password = request.POST.get('password')
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = authenticate(username=username,password=password)
            if user:
                if user.is_active:
                    login(request,user)
                    return render(request,'mock/base.html',{})
                else:
                    return render(request, 'users/login.html', {'msg': '用户未激活'})
            else:
                return render(request,'users/login.html',{'msg':'用户名密码不匹配'})
        else:
            return  render(request,'users/login.html',{'login_form':login_form})

class RegisterView(View):
    def get(self,request):
        register_form = RegisterForm()
        return render(request,'users/register.html',{'register_form':register_form})

    def post(self,request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = register_form.cleaned_data['email']
            user_profile = UserProfile.objects.get(email=email)
            if user_profile:
                return render(request,'users/register.html',{'msg':'邮箱已被注册'})
            else:
                password = register_form.cleaned_data['password']

                user = UserProfile()
                user.username = email
                user.email = email
                user.password = make_password(password)
                user.phone = '13333333333'
                user.is_active = 0
                user.save()
                send_cus_mail(email,'register')
                return HttpResponse('请登录注册邮箱，激活账号!!!!')

        else:
            return render(request,'users/register.html',{'register_form':register_form})

class ActiceUserView(View):
    def get(self,request,active_code):
        # 通过 active_code 获取 EmailVerfyRecord对象 假设code唯一
        email_verify_record = EmailVerifyRecord.objects.get(code=active_code[0:-1])

        user_profile = UserProfile.objects.get(email=email_verify_record.email)
        user_profile.is_active = True
        user_profile.save()
        return render(request,'users/login.html',{})

        # return HttpResponse(active_code)

    # 根据激活码 ---用户邮箱 ---用户姓名 --- 激活状态  |   注册信息错误返回信息   信息回溯 返回之后数据还是那样

